package com.qdu.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;

import com.qdu.bean.Consumable;

import com.qdu.commons.Result;
import com.qdu.exception.HouseException;
import com.qdu.service.ConsumableService;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/consumable")
public class ConsumableController {

    @Autowired
    ConsumableService consumableService;

    @RequestMapping("/getconsumable")
    public Result<List<Consumable>> getConsumable(){
        List<Consumable> consumableList = consumableService.queryAllConsumable();
        return Result.success(consumableList);
    }
    @RequestMapping("/updateConsumable")
    public Result<String> updateConsumable( Consumable consumable){
        try {
            consumableService.updateStore(consumable.getId());

        } catch (Exception e) {
            e.printStackTrace();
            throw new HouseException("出现了意料之外的情况");
        }

        return Result.success("消耗成功");

    }
    @RequestMapping("/orderConsumable")
    public Result<String> orderConsumable(Consumable consumable){
        boolean isTrue = consumableService.orderConsumable(consumable);
        return Result.success("成功");
    }

    @RequestMapping("/doExcel")
    public void doExcel(HttpServletResponse response){

        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("消耗品明细.xlsx", "UTF-8"));
            List<Consumable> consumableList = consumableService.queryAllConsumable();
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("消耗品明细", "消耗品明细.xlsx"), Consumable.class, consumableList);


            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new HouseException("出现了意料之外的情况");

        }


    }
}
